<template>
    <!--表单组件:并非行内-->
    <el-form label-width="80px">
        <el-form-item label="SPU名称"> xxxxxx </el-form-item>
        <el-form-item label="SKU名称">
            <el-input placeholder="请你输入SKU名称" v-model="skuParams.skuName"></el-input>
        </el-form-item>
        <el-form-item label="价格(元)">
            <el-input type="number" placeholder="价格(元)" v-model="skuParams.price"></el-input>
        </el-form-item>
        <el-form-item label="重量(千克)">
            <el-input type="number" placeholder="重量(千克)" v-model="skuParams.weight"></el-input>
        </el-form-item>
        <el-form-item label="规格描述">
            <el-input type="textarea" placeholder="规格描述" v-model="skuParams.skuDesc"></el-input>
        </el-form-item>
        <!--平台属性-->
        <el-form-item label="平台属性">
            <!--行内form:因为一行放置多个select-->
            <el-form :inline="true">
                <el-form-item :label="attr.attrName" v-for="(attr,index) in attrArr" :key="attr.id">
                    <el-select v-model="attr.attrIdAndValueId">
                        <el-option :label="item.valueName" :value="`${attr.id}:${item.id}`"
                            v-for="(item,index) in attr.attrValueList" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>
        <el-form-item label="销售属性">
            <!--行内form:因为一行放置多个select-->
            <el-form :inline="true">
                <el-form-item :label="saleAttr.saleAttrName" v-for="(saleAttr, index) in saleArr" :key="saleAttr.id">
                    <el-select v-model="saleAttr.saleAttrIdAndValueId">
                        <el-option :label="item.saleAttrValueName" :value="`${saleAttr.id}:${item.id}`"
                            v-for="(item, index) in saleAttr.spuSaleAttrValueList" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>
        <el-form-item label="图片名称">
            <el-table border :data="imgArr" ref="tableRef">
                <el-table-column width="80" type="selection"></el-table-column>
                <el-table-column label="图片">
                    <template #="{ row, $index }">
                        <img :src="row.imgUrl" alt="图片没了" style="width: 100px; height: 100px" />
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="imgName"></el-table-column>
                <el-table-column label="操作">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" v-if="row.isChecked == 1">默认</el-button>
                        <el-button type="info" size="small" v-else @click="changeChecked(row)">设置默认</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="default" @click="save">保存</el-button>
            <el-button size="default" @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
//平台属性|销售属性|照片墙
import { reqAttrList, reqSpuHasSaleAttr, reqImgList, reqAddSku } from '@/api/product/spu/spu'
//组合式API
import { ref } from 'vue';
import { ElMessage } from "element-plus";
//储存平台属性
let attrArr = ref([]);
//储存销售属性
let saleArr = ref([]);
//储存照片墙属性
let imgArr = ref([]);
//获取table组件
let tableRef = ref();
//收集添加SKU参数
let skuParams = ref<any>({
    //父组件传递过来的数据
    category3Id: 0,//三级分类的ID
    spuId: 0,//SPU的ID
    tmId: 0,//spu的品牌的ID

    // v-model收集的参数
    skuName: '',//sku的名字
    price: 0,//sku的价格
    weight: '',//sku的重量
    skuDesc: '',//sku的描述

    skuDefaultImg: '',//默认图片地址
    skuAttrValueList: [
        //平台属性
        // {
        //     attrId:0,//属性的ID
        //     valueId:0,//属性值的ID
        // },
    ],
    skuSaleAttrValueList: [
        //销售属性
        // {
        //     saleAttrId:0,
        //     saleAttrValueId:0,
        // },
    ],
});
//父组件点击sku添加按钮调用
const initSku = async (c1Id: number | string, c2Id: number | string, spu: any) => {
    //手机三级分类的ID|SPUID|TMID
    skuParams.value.category3Id = spu.category3Id;
    skuParams.value.spuId = spu.id;
    skuParams.value.tmId = spu.tmId;
    //平台属性
    let result = await reqAttrList(c1Id, c2Id, spu.category3Id);
    //销售属性
    let result1 = await reqSpuHasSaleAttr(spu.id);
    //照片墙属性
    let result2 = await reqImgList(spu.id);
    //储存平台属性
    attrArr.value = result;
    //储存销售属性
    saleArr.value = result1;
    //储存照片墙属性
    imgArr.value = result2;

    if (imgArr.value.length == 0) return;
    //由于服务器返回的数据没有控制默认按钮标记，只能自己手动添加，添加一个字段isChecked 1默认，0不是默认
    imgArr.value[0].isChecked = 1;
    setTimeout(() => {
        console.log(tableRef.value);
        tableRef.value.toggleRowSelection(imgArr.value[0], true);

        skuParams.value.skuDefaultImg = imgArr.value[0].imgUrl;
    }, 0);
    //添加isChecked = 0；
    for (var i = 0; i < imgArr.value.length - 1; i++) {
        if (i > 0) {
            imgArr.value[i].isChecked = 0;
        }
    }
};
//切换checked
const changeChecked = (row) => {
    //全部图片先变成0
    imgArr.value.forEach((item) => {
        item.isChecked = 0;
        //全部table复选框不勾选
        tableRef.value.toggleRowSelection(item, false);
    });
    //选中图片设置为默认
    row.isChecked = 1;
    //table组件实例：toggleRowSelection 设置某一行能否被选中
    tableRef.value.toggleRowSelection(row, true);
    //收集服务器需要携带的参数
    skuParams.value.skuDefaultImg = row.imgUrl;
};
//保存按钮
const save = async () => {
    //整体参数
    //整理平台属性
    skuParams.value.skuAttrValueList = attrArr.value.reduce((prev, next) => {
        //next:当前平台属性数组里面每一个元素
        //判断：当前平台属性对象是否有attrIdAndValueId属性，如果有说明用户在这儿个属性里面勾选了
        if (next.attrIdAndValueId) {
            //把字符串切割为数组
            const [attrId, valueId] = next.attrIdAndValueId.split(':');
            //整理成对象添加数组里面：对象，分别储存属性ID与属性值的ID
            prev.push({ attrId, valueId });
        }
        return prev;
    }, []);
    //整理销售属性的数据
    //reduce：返回结果看，回调函数最后一个是返回结果
    skuParams.value.skuSaleAttrValueList = saleArr.value.reduce((prev, next) => {
        if (next.saleAttrIdAndValueId) {
            const [saleAttrId, saleAttrIdAndValueId] = next.saleAttrIdAndValueId.split(':');
            prev.push({ saleAttrId, saleAttrIdAndValueId });
        }
        return prev;
    }, []);
    //发请求，添加sku
    try {
        await reqAddSku(skuParams.value);
        //请求成功：通知父组件切换场景.
        //提示细腻
        ElMessage({
            type: 'success',
            message: '添加SKU成功',
        });
        emit('changeScene', { scenes: 0, flag: '' });
        //清空数据
        resetData();
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '添加SKU失败',
        });
    }
};
//重置数据方法
const resetData = () => {
    attrArr.value = [];
    saleArr.value = [];
    imgArr.value = [];
    skuParams.value = {};
};
//取消的方法
const cancel =()=>{
    //触发自定义事件
    emit('changeScene',{scenes:0,flag:''});
    resetData();
}
// 对外暴露组件
defineExpose({
    initSku,
});
let emit = defineEmits(['changeScene']);
</script>

<style scoped>

</style>